package com.zw.mes.module.prodtaskmanager.service;

import com.zw.mes.common.JsonResult;
import com.zw.mes.module.prodtaskmanager.entity.ProdOrd;
import com.zw.mes.module.prodtaskmanager.entity.ProdOrdCha;
import com.zw.mes.module.prodtaskmanager.entity.VwPreEnquiryFile;
import com.zw.mes.module.prodtaskmanager.entity.VwProject;
import com.zw.mes.module.prodtaskmanager.mapper.ProdOrdMapper;
import com.zw.mes.module.prodtaskmanager.model.*;
import com.zw.mes.module.system.service.LogService;
import com.zw.mes.util.ShiroUtils;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 徐一贺
 * @className ProdOrdService
 * @description 生产令业务逻辑层
 * @date 2021/1/11 15:52
 * @versron ver 1.0
 */
@Log4j2
@Service
public class ProdOrdService {

  private ProdOrdMapper prodOrdMapper;

  @Autowired
  private void setProdOrdMapper(ProdOrdMapper ProdOrdMapper) {
    this.prodOrdMapper = ProdOrdMapper;
  }

  private LogService logService;

  @Autowired
  private void setLogService(LogService logService) {
    this.logService = logService;
  }

  /**
   * prodReleaseList 生产令任务下达页列表
   *
   * @param param 搜索参数
   * @return java.util.List<com.zw.mes.module.prodtaskmanager.model.ProdOrdModel>
   * @author 徐一贺
   * @date 2021/1/14 8:08
   */
  public List<ProdOrdModel> prodReleaseList(ProdOrdModel param) {
    return prodOrdMapper.findProdReleaseListByParam(param);
  }

  /**
   * getProInfo 通过项目表主键获取项目信息
   *
   * @param proId 项目表主键
   * @return com.zw.mes.module.prodtaskmanager.model.VwProjectModel
   * @author 徐一贺
   * @date 2021/1/14 9:00
   */
  public Map<String, Object> getProInfo(Integer proId) {
    Map<String, Object> data = new HashMap<>();
    VwProjectModel projectModel = prodOrdMapper.getProjectByPrimaryKey(proId);
    data.put("project", projectModel);
    data.put("files", prodOrdMapper.findFilesListByEnquiryIdAnProId(projectModel));
    return data;
  }

  /**
   * getVwPreEnquiryFileById 根据主键获取文件实体
   *
   * @param id 主键
   * @return com.zw.mes.module.prodtaskmanager.entity.VwPreEnquiryFile
   * @author 徐一贺
   * @date 2021/1/14 12:58
   */
  public VwPreEnquiryFile getVwPreEnquiryFileById(Integer id) {
    return prodOrdMapper.getVwPreEnquiryFileByPrimaryKey(id);
  }

  /**
   * getVwProjectByFileId 根据文件主键获取项目信息
   *
   * @param id 文件主键
   * @return com.zw.mes.module.prodtaskmanager.entity.VwProject
   * @author 徐一贺
   * @date 2021/1/14 13:00
   */
  public VwProject getVwProjectByFileId(Integer id) {
    return prodOrdMapper.getVwProjectByFileId(id);
  }

  /**
   * saveSplit 保存拆分结果
   *
   * @param proId
   * @param prodOrds
   * @return com.zw.mes.common.JsonResult
   * @author 徐一贺
   * @date 2021/1/14 16:57
   */
  @Transactional(rollbackFor = Exception.class)
  public JsonResult saveSplit(Integer proId, List<ProdOrd> prodOrds) {
    JsonResult jsonResult = new JsonResult();
    try {
      SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
      VwProjectModel vwProject = prodOrdMapper.getProjectByPrimaryKey(proId);
      List<ProdOrd> existProdOrds =
          prodOrdMapper.findProdOrdByProCodeAndNotDel(vwProject.getProCode());
      Integer prodNum = 0;
      for (ProdOrd item : prodOrds) {
        prodNum += item.getProdNum();
      }
      if (vwProject.getProQty().intValue() != prodNum) {
        jsonResult.setType(JsonResult.ResultType.ERROR);
        jsonResult.setMsg("尊敬的用户，您已创建此项目的数量发生改变，已与拆分的生产令数量之和不符，请刷新生产令任务下达页面后重新创建生产令！");
        return jsonResult;
      }
      if (existProdOrds.size() > 0) {
        jsonResult.setType(JsonResult.ResultType.ERROR);
        jsonResult.setMsg("尊敬的用户，您已创建此项目的生产令，不可再次创建！");
        return jsonResult;
      } else {
        String logContent = "<div style=\"border:green 1px solid;width:500px;\">被拆分的项目信息如下</div>";
        String cusDeliveryDate = "";
        if (vwProject.getCusDeliveryDate() != null) {
          cusDeliveryDate = vwProject.getCusDeliveryDate();
        }
        String customer = "";
        if (vwProject.getCustomer() != null) {
          customer = vwProject.getCustomer();
        }
        String insSite = "";
        if (vwProject.getInsSite() != null) {
          insSite = vwProject.getInsSite();
        }
        logContent +=
            "<div style=\"border:green 1px solid;width:500px;text-align:left;\">项目编号：【"
                + vwProject.getProCode()
                + "】</div>";
        logContent +=
            "<div style=\"border:green 1px solid;width:500px;text-align:left;\">项目名称：【"
                + vwProject.getProName()
                + "】</div>";
        logContent +=
            "<div style=\"border:green 1px solid;width:500px;text-align:left;\">项目数量：【"
                + vwProject.getProQty()
                + "】</div>";
        logContent +=
            "<div style=\"border:green 1px solid;width:500px;text-align:left;\">交货时间：【"
                + cusDeliveryDate
                + "】</div>";
        logContent +=
            "<div style=\"border:green 1px solid;width:500px;text-align:left;\">需方：【"
                + customer
                + "】</div>";
        logContent +=
            "<div style=\"border:green 1px solid;width:500px;text-align:left;\">安装地点：【"
                + insSite
                + "】</div>";
        String salesType = "";
        if (vwProject.getProType() == 1) {
          salesType = "对外";
        } else if (vwProject.getProType() == 2) {
          salesType = "对内";
        }
        String speEquipType = "";
        if (vwProject.getSpeEquipType() == 1) {
          speEquipType = "无";
        } else if (vwProject.getProType() == 2) {
          speEquipType = "起重机类";
        } else if (vwProject.getProType() == 3) {
          speEquipType = "压力管道类";
        }

        logContent +=
            "<div style=\"border:green 1px solid;width:500px;text-align:left;\">销售类型：【"
                + salesType
                + "】</div>";
        logContent +=
            "<div style=\"border:green 1px solid;width:500px;text-align:left;\">特种设备：【"
                + speEquipType
                + "】</div>";
        logContent +=
            "<div style=\"border:green 1px solid;width:500px;text-align:left;\">项目需求：【"
                + vwProject.getProRequirements()
                + "】</div>";
        logContent +=
            "<div style=\"border:green 1px solid;width:500px;text-align:left;\">制造范围：【"
                        + vwProject.getManufScope()
                    == null
                ? ""
                : vwProject.getManufScope() + "】</div>";
        logContent += "<div style=\"border:blue 1px solid;width:500px;\">拆分出的生产令信息如下</div>";
        for (int i = 0; i < prodOrds.size(); i++) {
          prodOrds.get(i).setProdIsIni((byte) 0);
          prodOrds.get(i).setProdManSta(1);
          prodOrds.get(i).setProdChaMat((byte) 1);
          prodOrds.get(i).setProdChaPur((byte) 1);
          prodOrds.get(i).setProdExeSta(1);
          prodOrdMapper.insertProdOrd(prodOrds.get(i));
          String type = "";
          if (prodOrds.get(i).getProdTyp() == 1) {
            type = "设备类";
          } else if (prodOrds.get(i).getProdTyp() == 2) {
            type = "其他";
          }
          String isKeyFlagStr = "";
          if (prodOrds.get(i).getProdIsKey() == 1) {
            isKeyFlagStr = "是";
          } else if (prodOrds.get(i).getProdIsKey() == 0) {
            isKeyFlagStr = "否";
          }
          logContent +=
              "<div style=\"border:blue 1px solid;width:500px;text-align:left;\">第"
                  + (i + 1)
                  + "个生产令信息如下：</div>";
          logContent +=
              "<div style=\"border:blue 1px solid;width:500px;text-align:left;\">生产令编号：【"
                  + prodOrds.get(i).getProdNo()
                  + "】</div>";
          logContent +=
              "<div style=\"border:blue 1px solid;width:500px;text-align:left;\">生产令数量：【"
                  + prodOrds.get(i).getProdNum()
                  + "】</div>";
          String prodDelDatStr = "";
          if (prodOrds.get(i).getProdDelDat() != null) {
            prodDelDatStr = formatter.format(prodOrds.get(i).getProdDelDat());
          }
          logContent +=
              "<div style=\"border:blue 1px solid;width:500px;text-align:left;\">交货期：【"
                  + prodDelDatStr
                  + "】</div>";
          logContent +=
              "<div style=\"border:blue 1px solid;width:500px;text-align:left;\">类别：【"
                  + type
                  + "】</div>";
          logContent +=
              "<div style=\"border:blue 1px solid;width:500px;text-align:left;\">是否是重点：【"
                  + isKeyFlagStr
                  + "】</div>";
          logContent +=
              "<div style=\"border:blue 1px solid;width:500px;text-align:left;\">产品分类：【"
                  + prodOrds.get(i).getProdBacTyp()
                  + "】</div>";
          String prodBacTypStr = "";
          if (prodOrds.get(i).getProdBacTyp() != null) {
            prodBacTypStr = prodOrds.get(i).getProdBacTyp();
          }
          logContent +=
              "<div style=\"border:blue 1px solid;width:500px;text-align:left;\">备件分类：【"
                  + prodBacTypStr
                  + "】</div>";
          String prodRemStr = "";
          if (prodOrds.get(i).getProdRem() != null) {
            prodRemStr = prodOrds.get(i).getProdRem();
          }
          logContent +=
              "<div style=\"border:blue 1px solid;width:500px;text-align:left;\">备注：【"
                  + prodRemStr
                  + "】</div>";
        }
        logService.saveLog("生产任务下达-->拆分生产令", logContent);
        jsonResult.setType(JsonResult.ResultType.SUCCESS);
        jsonResult.setMsg("保存成功！");
      }
    } catch (Exception e) {
      e.printStackTrace();
      log.error("【保存创建的拆分生产令异常】：" + e.getMessage());
      jsonResult.setType(JsonResult.ResultType.ERROR);
      jsonResult.setMsg("保存失败！");
    }
    return jsonResult;
  }

  /**
   * saveProdOrdUpdate 更新生产令信息
   *
   * @param prodOrd 生产令信息
   * @return com.zw.mes.common.JsonResult
   * @author 徐一贺
   * @date 2021/1/14 20:38
   */
  @Transactional(rollbackFor = Exception.class)
  public JsonResult saveProdOrdUpdate(ProdOrd prodOrd) {
    JsonResult jsonResult = new JsonResult();
    try {
      SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
      ProdOrd before = prodOrdMapper.getProdOrdByPrimaryKey(prodOrd.getProdId());
      prodOrdMapper.updateProdOrdByPrimaryKey(prodOrd);
      String beforeType = "";
      if (before.getProdTyp() == 1) {
        beforeType = "设备类";
      } else if (before.getProdTyp() == 2) {
        beforeType = "其他";
      }
      String beforeIsKeyFlagStr = "";
      if (before.getProdIsKey() == 1) {
        beforeIsKeyFlagStr = "是";
      } else if (before.getProdIsKey() == 0) {
        beforeIsKeyFlagStr = "否";
      }
      String afterType = "";
      if (prodOrd.getProdTyp() == 1) {
        afterType = "设备类";
      } else if (prodOrd.getProdTyp() == 2) {
        afterType = "其他";
      }
      String afterIsKeyFlagStr = "";
      if (prodOrd.getProdIsKey() == 1) {
        afterIsKeyFlagStr = "是";
      } else if (prodOrd.getProdIsKey() == 0) {
        afterIsKeyFlagStr = "否";
      }
      String deliveryTimeComparisonSymbol = "未改";
      String deliveryTimeComparisonSymbolStyle = "";
      if (!formatter
          .format(before.getProdDelDat())
          .equals(formatter.format(prodOrd.getProdDelDat()))) {
        deliveryTimeComparisonSymbol = "改";
        deliveryTimeComparisonSymbolStyle = ";color:red;";
      }
      String typeComparisonSymbol = "未改";
      String typeComparisonSymbolStyle = "";
      if (before.getProdTyp().intValue() != prodOrd.getProdTyp().intValue()) {
        typeComparisonSymbol = "改";
        typeComparisonSymbolStyle = ";color:red;";
      }
      String isKeyFlagComparisonSymbol = "未改";
      String isKeyFlagComparisonSymbolStyle = "";
      if (before.getProdIsKey().intValue() != prodOrd.getProdIsKey().intValue()) {
        isKeyFlagComparisonSymbol = "改";
        isKeyFlagComparisonSymbolStyle = ";color:red;";
      }
      String prodTypeFlagComparisonSymbol = "未改";
      String prodTypeComparisonSymbolStyle = "";
      if (!before.getProdBacTyp().equals(prodOrd.getProdBacTyp())) {
        prodTypeFlagComparisonSymbol = "改";
        prodTypeComparisonSymbolStyle = ";color:red;";
      }
      String logContent = "<div style=\"border:green 1px solid;width:500px;\">生产令更新信息如下：</div>";
      logContent +=
          "<div style=\"border:green 1px solid;width:225px;float:left\">更新前</div><div style=\"border:green 1px solid;width:50px;float:left\">&nbsp;</div><div style=\"border:green 1px solid;width:225px;float:left\">更新后</div>";
      logContent +=
          "<div style=\"border:green 1px solid;width:225px;float:left;clear:both\">生产令编号：【"
              + before.getProdNo()
              + "】</div><div style=\"border:green 1px solid;width:50px;float:left\">&nbsp;</div><div style=\"border:green 1px solid;width:225px;float:left\">生产令编号：【"
              + prodOrd.getProdNo()
              + "】</div>";
      logContent +=
          "<div style=\"border:green 1px solid;width:225px;float:left;clear:both\">生产令数量：【"
              + before.getProdNum()
              + "】</div><div style=\"border:green 1px solid;width:50px;float:left\">&nbsp;</div><div style=\"border:green 1px solid;width:225px;float:left\">生产令数量：【"
              + prodOrd.getProdNum()
              + "】</div>";
      logContent +=
          "<div style=\"border:green 1px solid;width:225px;float:left;clear:both\">交货期：【"
              + formatter.format(before.getProdDelDat())
              + "】</div><div style=\"border:green 1px solid;width:50px;float:left"
              + deliveryTimeComparisonSymbolStyle
              + "\">"
              + deliveryTimeComparisonSymbol
              + "</div><div style=\"border:green 1px solid;width:225px;float:left\">交货期：【"
              + formatter.format(prodOrd.getProdDelDat())
              + "】</div>";
      logContent +=
          "<div style=\"border:green 1px solid;width:225px;float:left;clear:both\">类别：【"
              + beforeType
              + "】</div><div style=\"border:green 1px solid;width:50px;float:left"
              + typeComparisonSymbolStyle
              + "\">"
              + typeComparisonSymbol
              + "</div><div style=\"border:green 1px solid;width:225px;float:left\">类别：【"
              + afterType
              + "】</div>";
      logContent +=
          "<div style=\"border:green 1px solid;width:225px;float:left;clear:both\">是否是重点：【"
              + beforeIsKeyFlagStr
              + "】</div><div style=\"border:green 1px solid;width:50px;float:left"
              + isKeyFlagComparisonSymbolStyle
              + "\">"
              + isKeyFlagComparisonSymbol
              + "</div><div style=\"border:green 1px solid;width:225px;float:left\">是否是重点：【"
              + afterIsKeyFlagStr
              + "】</div>";
      logContent +=
          "<div style=\"border:green 1px solid;width:225px;float:left;clear:both\">产品分类：【"
              + before.getProdBacTyp()
              + "】</div><div style=\"border:green 1px solid;width:50px;float:left"
              + prodTypeComparisonSymbolStyle
              + "\">"
              + prodTypeFlagComparisonSymbol
              + "</div><div style=\"border:green 1px solid;width:225px;float:left\">产品分类：【"
              + prodOrd.getProdBacTyp()
              + "】</div>";
      logService.saveLog("生产任务下达-->编辑生产令", logContent);
      jsonResult.setType(JsonResult.ResultType.SUCCESS);
      jsonResult.setMsg("保存成功！");
    } catch (Exception e) {
      e.printStackTrace();
      log.error("【保存生产令信息异常】：" + e.getMessage());
      jsonResult.setType(JsonResult.ResultType.ERROR);
      jsonResult.setMsg("保存失败！");
    }
    return jsonResult;
  }

  /**
   * getProdOrdByPrimaryKey 根据主键获取生产令对象
   *
   * @param id 主键
   * @return com.zw.mes.module.prodtaskmanager.entity.ProdOrd
   * @author 徐一贺
   * @date 2021/1/14 19:27
   */
  public ProdOrd getProdOrdByPrimaryKey(Integer id) {
    return prodOrdMapper.getProdOrdByPrimaryKey(id);
  }

  /**
   * removeProdOrd 删除生产令 删除相同项目编号下的所有生产令
   *
   * @param prodId 生产令主键
   * @return com.zw.mes.common.JsonResult
   * @author 徐一贺
   * @date 2021/1/15 9:59
   */
  @Transactional(rollbackFor = Exception.class)
  public JsonResult removeProdOrd(Integer prodId) {
    JsonResult jsonResult = new JsonResult();
    try {
      String logContent = "";
      ProdOrd ProdOrd = prodOrdMapper.getProdOrdByPrimaryKey(prodId);
      List<ProdOrdModel> prodOrdModels = prodOrdMapper.findProdOrdModelByProCodeAndNotDel(ProdOrd.getProdProCod());
      prodOrdMapper.deleteProdOrdByProCodeAndNotDel(ProdOrd.getProdProCod());
      logContent += "删除的生产令有：";
      for (int i = 0; i < prodOrdModels.size(); i++) {
        logContent += "【" + prodOrdModels.get(i).getProdNo() + "】、";
      }
      logContent = logContent.substring(0, logContent.length() - 1);
      logService.saveLog("生产任务下达-->删除生产令", logContent);
      jsonResult.setType(JsonResult.ResultType.SUCCESS);
      jsonResult.setMsg("删除成功！");
    } catch (Exception e) {
      e.printStackTrace();
      log.error("【删除生产令异常】：" + e.getMessage());
      jsonResult.setType(JsonResult.ResultType.ERROR);
      jsonResult.setMsg("删除失败！");
    }
    return jsonResult;
  }

  /**
   * submitProdOrd 提交生产令
   *
   * @param id 生产令主键
   * @return com.zw.mes.common.JsonResult
   * @author 徐一贺
   * @date 2021/1/15 10:24
   */
  @Transactional(rollbackFor = Exception.class)
  public JsonResult submitProdOrd(String id) {
    JsonResult jsonResult = new JsonResult();
    try {
      List<String> proCode = prodOrdMapper.findDifferentProCodePrimaryKeysByprodIds(id);
      String logContent = "";
      for (int i = 0; i < proCode.size(); i++) {
        ProdOrd prodOrd = new ProdOrd();
        prodOrd.setProdProCod(proCode.get(i));
        prodOrd.setProdSta(2);
        prodOrd.setProdRelDat(new Date());
        prodOrdMapper.updateProdOrdStatusByProCodeAndNotDel(prodOrd);
        List<ProdOrdModel> prodOrdModels =
            prodOrdMapper.findProdOrdModelByProCodeAndNotDel(prodOrd.getProdProCod());
        logContent = "项目编号为：【" + prodOrd.getProdProCod() + "】的生产令编号为";
        for (int j = 0; j < prodOrdModels.size(); j++) {
          logContent += "【" + prodOrdModels.get(j).getProdNo() + "】、";
        }
        logContent = logContent.substring(0, logContent.length() - 1) + "被下达了。";
      }
      logService.saveLog("生产任务下达-->提交生产令", logContent);
      jsonResult.setType(JsonResult.ResultType.SUCCESS);
      jsonResult.setMsg("提交成功！");
    } catch (Exception e) {
      e.printStackTrace();
      log.error("【提交生产令异常】：" + e.getMessage());
      jsonResult.setType(JsonResult.ResultType.ERROR);
      jsonResult.setMsg("提交失败！");
    }
    return jsonResult;
  }

  /**
   * stopProd 终止生产令
   *
   * @param param 终止信息
   * @return com.zw.mes.common.JsonResult
   * @author 徐一贺
   * @date 2021/2/3 10:56
   */
  @Transactional(rollbackFor = Exception.class)
  public JsonResult stopProd(ProdOrdModel param) {
    JsonResult jsonResult = new JsonResult();
    try {
      ProdOrd prodOrd = prodOrdMapper.getProdOrdByPrimaryKey(param.getProdId());
      param.setProdStoDat(new Date());
      param.setProdManSta(2);
      prodOrdMapper.updateProdOrdByStopPrimaryKey(param);
      logService.saveLog(
          "生产任务下达-->终止生产令",
          "编号为：【" + prodOrd.getProdNo() + "】生产令被终止！终止原因是：【" + param.getProdStoRea() + "】。");
      jsonResult.setType(JsonResult.ResultType.SUCCESS);
      jsonResult.setMsg("提交成功！");
    } catch (Exception e) {
      e.printStackTrace();
      log.error("【提交生产令异常】：" + e.getMessage());
      jsonResult.setType(JsonResult.ResultType.ERROR);
      jsonResult.setMsg("提交失败！");
    }
    return jsonResult;
  }

  /**
   * 获取已存在的生产令列表
   *
   * @param proCode 项目号
   * @author 徐一贺
   * @date 2021/2/21 11:09
   */
  public List<ProdOrdJsonModel> loadAlreadyExistsProdList(String proCode) {
    return prodOrdMapper.findProdOrdAndProjectByProCodeAndNotDel(proCode);
  }

  /**
   * 保存编辑生产令
   *
   * @param prodOrds 项目号
   * @author 徐一贺
   * @date 2021/2/21 13:53
   */
  @Transactional(rollbackFor = Exception.class)
  public JsonResult saveEdit(List<ProdOrdJsonModel> removeProdOrds, List<ProdOrdModel> prodOrds) {
    JsonResult jsonResult = new JsonResult();
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
    try {
      for (int i = 0; i < removeProdOrds.size(); i++) {
        prodOrdMapper.deleteProdOrdByPrimaryKey(removeProdOrds.get(i).getProdId());
        logService.saveLog("删除生产令", "生产令编号为【" + removeProdOrds.get(i).getProdNo() + "】的生产令已删除！");
      }
      for (ProdOrdModel prodOrd : prodOrds) {
        if (prodOrd.getProdId() != null) {
          ProdOrd before = prodOrdMapper.getProdOrdByPrimaryKey(prodOrd.getProdId());
          prodOrdMapper.updateProdOrdByPrimaryKey(prodOrd);
          String content = "";
          if (!before.getProdNo().equals(prodOrd.getProdNo())) {
            content += "生产令编号编辑前为：【" + before.getProdNo() + "】";
            content += "编辑后为：【" + prodOrd.getProdNo() + "】、";
          }
          if (before.getProdNum().intValue() != prodOrd.getProdNum().intValue()) {
            content += "生产令数量编辑前为：【" + before.getProdNum() + "】";
            content += "编辑后为：【" + prodOrd.getProdNum() + "】、";
          }
          if (before.getProdDelDat() == null && prodOrd.getProdDelDat() != null) {
            content += "生产令交货期编辑前为：【】";
            content += "编辑后为：【" + simpleDateFormat.format(prodOrd.getProdDelDat()) + "】、";
          } else if (before.getProdDelDat() != null && prodOrd.getProdDelDat() == null) {
            content += "生产令交货期编辑前为：【" + simpleDateFormat.format(prodOrd.getProdDelDat()) + "】";
            content += "编辑后为：【】、";
          } else if (before.getProdDelDat() == null && prodOrd.getProdDelDat() == null) {
            content += "生产令交货期编辑前为：【】";
            content += "编辑后为：【】、";
          } else if (before.getProdDelDat() != null
              && prodOrd.getProdDelDat() != null
              && !simpleDateFormat
                  .format(before.getProdDelDat())
                  .equals(simpleDateFormat.format(prodOrd.getProdDelDat()))) {
            content += "生产令交货期编辑前为：【" + simpleDateFormat.format(before.getProdDelDat()) + "】";
            content += "编辑后为：【" + simpleDateFormat.format(prodOrd.getProdDelDat()) + "】、";
          }
          if (before.getProdTyp() != prodOrd.getProdTyp()) {
            String beforeProdTyp = "";
            if (before.getProdTyp() == 1) {
              beforeProdTyp = "设备类";
            } else if (before.getProdTyp() == 2) {
              beforeProdTyp = "其他";
            }
            content += "生产令类别编辑前为：【" + beforeProdTyp + "】";
            String afterProdTyp = "";
            if (prodOrd.getProdTyp() == 1) {
              afterProdTyp = "设备类";
            } else if (prodOrd.getProdTyp() == 2) {
              afterProdTyp = "其他";
            }
            content += "编辑后为：【" + afterProdTyp + "】、";
          }
          if (before.getProdIsKey() != prodOrd.getProdIsKey()) {
            String beforeProdIsKey = "";
            if (before.getProdIsKey() == 1) {
              beforeProdIsKey = "是";
            } else if (before.getProdIsKey() == 0) {
              beforeProdIsKey = "否";
            }
            content += "生产令是否重点编辑前为：【" + beforeProdIsKey + "】";
            String afterProdIsKey = "";
            if (prodOrd.getProdIsKey() == 1) {
              afterProdIsKey = "是";
            } else if (prodOrd.getProdIsKey() == 0) {
              afterProdIsKey = "否";
            }
            content += "编辑后为：【" + afterProdIsKey + "】、";
          }
          if (!before.getProdBacTyp().equals(prodOrd.getProdBacTyp())) {
            content += "生产令产品分类编辑前为：【" + before.getProdBacTyp() + "】";
            content += "编辑后为：【" + prodOrd.getProdBacTyp() + "】、";
          }
          if (!before.getProdRem().equals(prodOrd.getProdRem())) {
            content += "生产令备注编辑前为：【" + before.getProdRem() + "】";
            content += "编辑后为：【" + prodOrd.getProdRem() + "】、";
          }
          if (content.length() > 0) {
            content = content.substring(0, content.length() - 1) + "。";
            logService.saveLog("保存编辑生产令", content);
          }
        } else {
          logService.saveLog("新增生产令", "新增生产令编号为【" + prodOrd.getProdNo() + "】");
          prodOrd.setProdManSta(1);
          prodOrd.setProdChaMat((byte) 1);
          prodOrd.setProdChaPur((byte) 1);
          prodOrd.setProdExeSta(1);
          prodOrdMapper.insertProdOrd(prodOrd);
        }
      }
      jsonResult.setType(JsonResult.ResultType.SUCCESS);
      jsonResult.setMsg("保存成功！");
    } catch (Exception e) {
      e.printStackTrace();
      log.error("保存编辑生产令异常：" + e.getMessage());
      jsonResult.setType(JsonResult.ResultType.ERROR);
      jsonResult.setMsg("保存失败！");
    }
    return jsonResult;
  }

  /**
   * 检测根据项目号检测数量
   *
   * @param num
   * @param prodProCod
   * @return
   */
  @Transactional(rollbackFor = Exception.class)
  public JsonResult checkNum(Integer num, String prodProCod) {
    JsonResult jsonResult = new JsonResult();
    try {
      VwProject vwProject = prodOrdMapper.getVwProjectByProCode(prodProCod);
      if (vwProject.getProQty().intValue() == num.intValue()) {
        jsonResult.setType(JsonResult.ResultType.SUCCESS);
      } else {
        jsonResult.setType(JsonResult.ResultType.ERROR);
        jsonResult.setMsg("尊敬的用户，您拆分的生产令的项目数量与项目的项目数量不符，请刷新页面重新修改后提交！");
      }
    } catch (Exception e) {
      e.printStackTrace();
      log.error("根据项目号检测数量错误，异常信息如下:" + e.getMessage());
      jsonResult.setType(JsonResult.ResultType.ERROR);
      jsonResult.setMsg("根据项目号检测数量失败！");
    }
    return jsonResult;
  }

  /**
   * 恢复生产令生产状态为正常
   *
   * @param prodId
   * @return
   */
  @Transactional(rollbackFor = Exception.class)
  public JsonResult cancelStopProd(Integer prodId) {
    JsonResult jsonResult = new JsonResult();
    try {
      SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      ProdOrd prodOrd = prodOrdMapper.getProdOrdByPrimaryKey(prodId);
      logService.saveLog(
          "恢复生产令状态为正常",
          "生产令编号为【"
              + prodOrd.getProdNo()
              + "】恢复正常！上次终止原因是【"
              + prodOrd.getProdStoRea()
              + "】，上次终止时间是【"
              + simpleDateFormat.format(prodOrd.getProdStoDat())
              + "】。");
      prodOrdMapper.updateProdOrdProdManStaToNormalByPrimaryKey(prodId);
      jsonResult.setType(JsonResult.ResultType.SUCCESS);
      jsonResult.setMsg("恢复成功！");
    } catch (Exception e) {
      e.printStackTrace();
      log.error("恢复生产令状态为正常失败，异常信息如下:" + e.getMessage());
      jsonResult.setType(JsonResult.ResultType.ERROR);
      jsonResult.setMsg("恢复失败！");
    }
    return jsonResult;
  }

  /**
   * 根据项目号获取项目信息
   *
   * @param prodProCod
   * @return
   */
  public VwProject getVwProjectByProCode(String prodProCod) {
    return prodOrdMapper.getVwProjectByProCode(prodProCod);
  }

  //    /**
  //     * 根据项目号获取生产令列表
  //     *
  //     * @param prodProCod
  //     * @return
  //     */
  //    public List<ProdOrdModel> findProdOrdByProdProCod(String prodProCod) {
  //        return prodOrdMapper.findProdOrdModelByProCodeAndNotDel(prodProCod);
  //    }

  /**
   * 比较修改后的生产令的数量与项目数量是否相等
   *
   * @param param
   * @return
   */
  public JsonResult checkNumByProdOrd(ProdOrdModel param) {
    JsonResult jsonResult = new JsonResult();
    try {
      VwProject vwProject = prodOrdMapper.getVwProjectByProCode(param.getProdProCod());
      Integer totalNum = prodOrdMapper.getProdOrdTotalNumByProdProCodAndNotAppointProdNoNum(param);
      if (vwProject.getProQty().intValue() == totalNum + param.getProdNum()) {
        jsonResult.setType(JsonResult.ResultType.SUCCESS);
      } else {
        jsonResult.setType(JsonResult.ResultType.ERROR);
        jsonResult.setMsg("请保证修改后的数量与已存在的生产令数量之和与项目数量相等！");
      }
    } catch (Exception e) {
      e.printStackTrace();
      log.error("比较修改后的生产令的数量与项目数量是否相等失败，异常信息如下:" + e.getMessage());
      jsonResult.setType(JsonResult.ResultType.ERROR);
      jsonResult.setMsg("比较修改后的生产令的数量与项目数量是否相等失败！");
    }
    return jsonResult;
  }

  /**
   * 保存生产令变更
   *
   * @param dataList
   * @returncommon
   */
  @Transactional(rollbackFor = Exception.class)
  public JsonResult saveChange(List<ProdOrdModel> dataList, String clientIp) {
    JsonResult jsonResult = new JsonResult();
    try {
      String release = "";
      for (int i = 0; i < dataList.size(); i++) {
        ProdOrdModel prodOrdModel = dataList.get(i);
        if (prodOrdModel.getProdId() != null) {
          ProdOrd before = prodOrdMapper.getProdOrdByPrimaryKey(prodOrdModel.getProdId());
          ProdOrd after = prodOrdModel;
          ProdOrdCha prodOrdCha = new ProdOrdCha();
          prodOrdCha.setProcProCod(before.getProdProCod());
          prodOrdCha.setProcProdNo(before.getProdNo());
          prodOrdCha.setBefNum(before.getProdNum());
          prodOrdCha.setBefTyp(before.getProdTyp());
          prodOrdCha.setBefBacTyp(before.getProdBacTyp());
          prodOrdCha.setBefIsKey(before.getProdIsKey());
          prodOrdCha.setBefDelDat(before.getProdDelDat());
          prodOrdCha.setBefRem(before.getProdRem());
          prodOrdCha.setAftNum(after.getProdNum());
          prodOrdCha.setAftTyp(after.getProdTyp());
          prodOrdCha.setAftBacTyp(after.getProdBacTyp());
          prodOrdCha.setAftIsKey(after.getProdIsKey());
          prodOrdCha.setAftDelDat(after.getProdDelDat());
          prodOrdCha.setAftRem(after.getProdRem());
          prodOrdCha.setProcChaRea(prodOrdModel.getChangeReason());
          prodOrdCha.setProcChaDat(new Date());
          prodOrdCha.setProcChaUsrId(ShiroUtils.getUserId());
          prodOrdCha.setProcOs(prodOrdModel.getOs());
          prodOrdCha.setProcBrowser(prodOrdModel.getBrowser());
          prodOrdCha.setProcIp(clientIp);
          prodOrdMapper.insertProdOrdCha(prodOrdCha);
          prodOrdMapper.updateProdOrdChangeByPrimaryKey(prodOrdModel);
          String content = "";
          if (prodOrdCha.getBefNum().intValue() != prodOrdCha.getAftNum().intValue()) {
            content += "项目数量变更前为【" + prodOrdCha.getBefNum().intValue() + "】，";
            content += "变更后为【" + prodOrdCha.getAftNum().intValue() + "】、";
          }
          if (prodOrdCha.getBefTyp().intValue() != prodOrdCha.getAftTyp().intValue()) {
            String befTypStr = "";
            if (prodOrdCha.getBefTyp().intValue() == 1) {
              befTypStr = "设备类";
            } else if (prodOrdCha.getBefTyp().intValue() == 2) {
              befTypStr = "其他类";
            }
            String aftTypStr = "";
            if (prodOrdCha.getAftTyp().intValue() == 1) {
              aftTypStr = "设备类";
            } else if (prodOrdCha.getAftTyp().intValue() == 2) {
              aftTypStr = "其他类";
            }
            content += "类型变更前为【" + befTypStr + "】，";
            content += "变更后为【" + aftTypStr + "】、";
          }
          if (prodOrdCha.getBefIsKey().intValue() != prodOrdCha.getAftIsKey().intValue()) {
            String befIsKeyStr = "";
            if (prodOrdCha.getBefIsKey().intValue() == 1) {
              befIsKeyStr = "是";
            } else if (prodOrdCha.getBefIsKey().intValue() == 0) {
              befIsKeyStr = "否";
            }
            String aftIsKeyStr = "";
            if (prodOrdCha.getAftIsKey().intValue() == 1) {
              aftIsKeyStr = "是";
            } else if (prodOrdCha.getAftIsKey().intValue() == 0) {
              aftIsKeyStr = "否";
            }
            content += "是否重点变更前为【" + befIsKeyStr + "】，";
            content += "变更后为【" + aftIsKeyStr + "】、";
          }
          String beforeDelDat = "";
          SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
          if(prodOrdCha.getBefDelDat()!=null){
            beforeDelDat = formatter.format(prodOrdCha.getBefDelDat());
          }
          String afterDelDat = "";
          if(prodOrdCha.getAftDelDat()!=null){
            afterDelDat = formatter.format(prodOrdCha.getAftDelDat());
          }
          if (!beforeDelDat.equals(afterDelDat)) {
            content += "交货时间变更前为【" + beforeDelDat + "】，";
            content += "变更后为【" + afterDelDat + "】、";
          }
          if (prodOrdCha.getBefRem() != null && prodOrdCha.getAftRem() == null) {
            content += "备注变更前为【" + prodOrdCha.getBefRem() + "】，";
            content += "变更后为【】、";
          }
          if (prodOrdCha.getBefRem() == null && prodOrdCha.getAftRem() != null) {
            content += "备注变更前为【】，";
            content += "变更后为【" + prodOrdCha.getAftRem() + "】、";
          }
          if (prodOrdCha.getBefRem() != null
              && prodOrdCha.getAftRem() != null
              && !prodOrdCha.getBefRem().equals(prodOrdCha.getAftRem())) {
            content += "备注变更前为【" + prodOrdCha.getBefRem() + "】，";
            content += "变更后为【" + prodOrdCha.getAftRem() + "】、";
          }
          if (content.length() > 0) {
            content = content.substring(0, content.length() - 1);
            content += "，变更原因：【" + prodOrdCha.getProcChaRea() + "】。";
            content =
                "项目编号为【"
                    + prodOrdCha.getProcProCod()
                    + "】，编号为【"
                    + prodOrdCha.getProcProdNo()
                    + "】的生产令的"
                    + content;
            logService.saveLog("生产令变更", content);
          }
        } else {
          prodOrdModel.setProdIsIni((byte) 0);
          prodOrdModel.setProdChaMat((byte) 1);
          prodOrdModel.setProdChaPur((byte) 1);
          prodOrdModel.setProdExeSta(1);
          prodOrdMapper.insertProdOrd(prodOrdModel);
          String content =
              "新增项目编号为【"
                  + prodOrdModel.getProdProCod()
                  + "】，编号为【"
                  + prodOrdModel.getProdNo()
                  + "】的生产令的";
          content += "项目数量为【" + prodOrdModel.getProdNum().intValue() + "】，";
          String typStr = "";
          if (prodOrdModel.getProdTyp().intValue() == 1) {
            typStr = "设备类";
          } else if (prodOrdModel.getProdTyp().intValue() == 2) {
            typStr = "其他类";
          }
          content += "类型为【" + typStr + "】，";
          String isKeyStr = "";
          if (prodOrdModel.getProdIsKey().intValue() == 1) {
            isKeyStr = "是";
          } else if (prodOrdModel.getProdIsKey().intValue() == 0) {
            isKeyStr = "否";
          }
          content += "是否重点为【" + isKeyStr + "】，";
          SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
          content += "交货时间为【" + simpleDateFormat.format(prodOrdModel.getProdDelDat()) + "】，";
          content += "备注为【" + prodOrdModel.getProdRem() + "】，";
          content += "。";
          logService.saveLog("生产令变更-新增生产令", content);
          release += "【" + prodOrdModel.getProdNo() + "】、";
        }
      }
      jsonResult.setType(JsonResult.ResultType.SUCCESS);
      if (release.length() > 0) {
        release = release.substring(0, release.length() - 1);
        release = ",但是新增了编号为" + release + "的生产令，这些生产令需要下达。";
      }
      jsonResult.setMsg("保存生产令变成成功" + release + "！");
    } catch (Exception e) {
      e.printStackTrace();
      log.error("保存生产令变成失败，异常信息如下:" + e.getMessage());
      jsonResult.setType(JsonResult.ResultType.ERROR);
      jsonResult.setMsg("保存生产令变成失败！");
    }
    return jsonResult;
  }

  /**
   * 检测与数据库中的数据是否相等
   *
   * @param param
   * @return
   */
  public JsonResult checkIsSame(ProdOrd param) {
    JsonResult jsonResult = new JsonResult();
    try {
      ProdOrd before = prodOrdMapper.getProdOrdByPrimaryKey(param.getProdId());
      ProdOrd after = param;
      if (before.getProdNum().intValue() == after.getProdNum().intValue()
          && before.getProdTyp().intValue() == after.getProdTyp().intValue()
          && before.getProdBacTyp().equals(after.getProdBacTyp())
          && before.getProdIsKey().intValue() == after.getProdIsKey().intValue()
          && before.getProdDelDat().compareTo(after.getProdDelDat()) == 0
          && before.getProdRem().equals(after.getProdRem())) {
        jsonResult.setType(JsonResult.ResultType.ERROR);
        jsonResult.setMsg("您未对生产令信息作出修改，请修改后保存！");
      } else {
        jsonResult.setType(JsonResult.ResultType.SUCCESS);
      }
    } catch (Exception e) {
      e.printStackTrace();
      log.error("检测与数据库中的数据是否相等失败，异常信息如下:" + e.getMessage());
      jsonResult.setType(JsonResult.ResultType.ERROR);
      jsonResult.setMsg("检测与数据库中的数据是否相等失败！");
    }
    return jsonResult;
  }

  /**
   * changeQueryList 生产令变更记录查询
   *
   * @param param 搜索参数
   * @return List<ProdOrdChaModel> 搜索结果
   * @author 徐一贺
   * @date 2021/2/23 11:22
   */
  public List<ProdOrdChaModel> findChangeQueryList(ProdOrdChaModel param) {
    return prodOrdMapper.findChangeQueryList(param);
  }

  /**
   * 生产任务管理待处理项目数提示
   *
   * @return
   */
  public JsonResult getProdTaskManPenItemPromptNum() {
    Map<String, Integer> result = new HashMap<>();
    // 生产令下达数量
    result.put("prodOrdReleaseNum", prodOrdMapper.getProdOrdReleaseNum());
    // 排产任务池数量
    result.put("schedulingNum", prodOrdMapper.getSchedulingNum());
    // 普通任务池数量
    result.put("commonNum", prodOrdMapper.getCommonNum());
    // 科级总调计划审核数量
    result.put("auditNum", prodOrdMapper.getAuditNum());
    // 部级总调计划审核数量
    result.put("auditMinisterialNum", prodOrdMapper.getAuditMinisterialNum());
    JsonResult jsonResult = new JsonResult();
    jsonResult.setType(JsonResult.ResultType.SUCCESS);
    jsonResult.setData(result);
    return jsonResult;
  }

  /**
   * 加载项目文件查询页项目列表
   *
   * @param param
   * @return
   */
  public List<ProjectByAttachmentListModel> loadProjectByAttachmentList(
      ProjectByAttachmentListModel param) {
    return prodOrdMapper.findProjectByAttachmentListByParam(param);
  }

  /**
   * 根据条件查询销售系统的询价单附件、项目任务单附件、项目附件、技术协议这四种类型的文件列表
   *
   * @param param
   * @return
   */
  public List<FileListModel> loadProjectAttachmentList(FileListModel param) {
    return prodOrdMapper.findProjectAttachmentList(param);
  }

  /**
   * 获取询价单附件模型类
   *
   * @param fileId
   * @return
   */
  public FileListModel getInquirySheetAttachmentByFileId(Integer fileId) {
    return prodOrdMapper.getInquirySheetAttachmentByFileId(fileId);
  }
  /**
   * 获取项目附件模型类
   *
   * @param fileId
   * @return
   */
  public FileListModel getProjectAttachmentByFileId(Integer fileId) {
    return prodOrdMapper.getProjectAttachmentByFileId(fileId);
  }
  /**
   * 获取及时文件模型类
   *
   * @return
   */
  public FileListModel getTechnicalAgreementAttachmentByFileId(Integer fileId) {
    return prodOrdMapper.getTechnicalAgreementAttachmentByFileId(fileId);
  }

  private String saleFilePath = "/salefiles/";

  /**
   * 查询任务单
   *
   * @param proInvId
   * @return
   */
  public ProjectInvoiceModel selectProInvoInfoById(Integer proInvId) {
    ProjectInvoiceModel projectInvoiceModel = prodOrdMapper.selectProInvoInfoById(proInvId);
    if (projectInvoiceModel.getProSecLeaderSign() != null) {
      projectInvoiceModel.setProSecLeaderSign(
          saleFilePath + projectInvoiceModel.getProSecLeaderSign().substring(7));
    }
    if (projectInvoiceModel.getTechLeaderSign() != null) {
      projectInvoiceModel.setTechLeaderSign(
          saleFilePath + projectInvoiceModel.getTechLeaderSign().substring(7));
    }
    if (projectInvoiceModel.getProdLeaderSign() != null) {
      projectInvoiceModel.setProdLeaderSign(
          saleFilePath + projectInvoiceModel.getProdLeaderSign().substring(7));
    }
    return projectInvoiceModel;
  }

  /**
   * 根据主键
   *
   * @param proId
   * @return
   */
  public VwProject getVwProjectByPrimaryKey(Integer proId) {
    return prodOrdMapper.getVwProjectByPrimaryKey(proId);
  }

  /**
   * @methodName: postponementProdOrd
   * @description: 生产令暂缓
   * @param: param 暂缓参数
   * @return： com.zw.mes.common.JsonResult
   * @exception：
   * @author： 徐一贺
   * @date： 2021/3/23 12:39
   * @office: 智能控制设计科
   * @research institute： 智能控制设计所
   * @department： 机械设计院
   * @company: 辽宁忠旺机械设备制造有限公司
   * @group： 忠旺集团
   * @version: 1.0
   */
  @Transactional(rollbackFor = Exception.class)
  public JsonResult postponementProdOrd(ProdOrdModel param) {
    JsonResult jsonResult = new JsonResult();
    try {
      ProdOrd prodOrd = prodOrdMapper.getProdOrdByPrimaryKey(param.getProdId());
      param.setProdManSta(3);
      param.setProdStoDat(new Date());
      prodOrdMapper.updateProdOrdProdManStaByPrimaryKey(param);
      logService.saveLog("生产令下达-生产令暂缓","生产令编号为【"+prodOrd.getProdNo()+"】被设置成暂缓！");
      jsonResult.setType(JsonResult.ResultType.SUCCESS);
      jsonResult.setMsg("生产令暂缓成功！");
    } catch (Exception e) {
      e.printStackTrace();
      log.error("生产令暂缓异常："+e.getMessage());
      jsonResult.setType(JsonResult.ResultType.ERROR);
      jsonResult.setMsg("生产令暂缓失败！");
    }
    return jsonResult;
  }
}
